﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using FanjiaHotelPlatform.utils.Kits;
using log4net.Repository.Hierarchy;
using Newtonsoft.Json;
using Polly;
using Polly.Timeout;

namespace WindowsFormsApplication1
{
    public partial class Form6 : Form
    {
        public Form6()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                var apiUrl = $"http://jinjianghoteltest.fanjiaxing.com/api/Hotel/GetHotelRoomList";
                var req = new HotelRoomStatusReq
                {
                    InnId = "5573",
                    EndOfDay = "2020-05-26",
                    Days = 2
                };

                var policy = Policy.Timeout(3);
                var cancellationToken = new CancellationToken();

                policy.Execute((token) =>
                {

                    var resultDto = WebRequestKit.PostAsJsonAsync<ApiResponse<Object>>(apiUrl, req).GetAwaiter().GetResult();
                    if (resultDto != null && resultDto.MsgCode == "0")
                    {
                        var retStr = JsonConvert.SerializeObject(resultDto.Result);
                        MessageBox.Show(retStr);
                    }
                    else
                    {
                        MessageBox.Show($"QueryRatePlanInfoAsync，HotelId:{req.InnId}，请求锦江之星接口获取酒店房价房型信息。{resultDto?.Message}");
                    }
                    Console.WriteLine(token.IsCancellationRequested);
                }, cancellationToken);               

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 酒店房态接口请求参数
        /// </summary>
        public class HotelRoomStatusReq
        {
            /// <summary>
            /// 酒店唯一编号
            /// </summary>
            public string InnId { get; set; }
            /// <summary>
            /// 房型编号(1001 大床房 1002 经济房…)
            /// </summary>
            public string RoomTypeCode { get; set; }
            /// <summary>
            /// 营业日期(yyyy-MM-dd)
            /// </summary>
            public string EndOfDay { get; set; }
            /// <summary>
            /// 查询天数(默认1天)
            /// </summary>
            public int Days { get; set; }
        }

        public class ApiResponse
        {
            /// <summary>
            /// 返回结果Code,0为正常
            /// </summary>
            public string MsgCode { get; set; }

            /// <summary>
            /// 错误信息
            /// </summary>
            public string Message { get; set; }

            public string HotelMsgCode { get; set; }
        }

        public class ApiResponse<T> : ApiResponse
        {
            public T Result { get; set; }
        }

        private async void button2_Click(object sender, EventArgs e)
        {
            //var policy = Policy.TimeoutAsync(2, TimeoutStrategy.Pessimistic);
            ////var cts = new CancellationTokenSource();

            //var apiUrl = $"http://jinjianghoteltest.fanjiaxing.com/api/Hotel/GetHotelRoomList";
            //var req = new HotelRoomStatusReq
            //{
            //    InnId = "5573",
            //    EndOfDay = "2020-05-26",
            //    Days = 2
            //};

            //try
            //{
            //    var rst = policy.ExecuteAsync(async () =>
            //    {
            //        Thread.Sleep(5000);

            //        //var resultDto = await WebRequestKit.PostAsJsonAsync<ApiResponse<Object>>(apiUrl, req);//.GetAwaiter().GetResult();
            //        //if (resultDto != null && resultDto.MsgCode == "0")
            //        //{
            //        //    var retStr = JsonConvert.SerializeObject(resultDto.Result);
            //        //    MessageBox.Show(retStr);
            //        //}
            //        //else
            //        //{
            //        //    MessageBox.Show(
            //        //        $"QueryRatePlanInfoAsync，HotelId:{req.InnId}，请求锦江之星接口获取酒店房价房型信息。{resultDto?.Message}");
            //        //}
            //    });
            //}
            //catch (Exception exception)
            //{
            //    Console.WriteLine(exception);
            //    throw;
            //}

            var apiUrl = $"http://jinjianghoteltest.fanjiaxing.com/api/Hotel/GetHotelRoomList";
            var req = new HotelRoomStatusReq
            {
                InnId = "5573",
                EndOfDay = "2020-05-26",
                Days = 2
            };

            //Policy policy = Policy.Handle<Exception>() //定义所处理的故障
            //    .Fallback(() =>
            //    {
            //        MessageBox.Show("执行出错");
            //    });

            //policy = policy.Wrap(Policy.Timeout(2, TimeoutStrategy.Pessimistic));
            //policy.Execute(() =>
            //{
            //    Console.WriteLine("开始任务");
            //    Thread.Sleep(5000);

            //    var resultDto = WebRequestKit.PostAsJsonAsync<ApiResponse<Object>>(apiUrl, req).GetAwaiter().GetResult();
            //    if (resultDto != null && resultDto.MsgCode == "0")
            //    {
            //        var retStr = JsonConvert.SerializeObject(resultDto.Result);
            //        MessageBox.Show(retStr);
            //    }
            //    else
            //    {
            //        MessageBox.Show(
            //            $"QueryRatePlanInfoAsync，HotelId:{req.InnId}，请求锦江之星接口获取酒店房价房型信息。{resultDto?.Message}");
            //    }

            //    Console.WriteLine("完成任务");
            //});

            try
            {
                ISyncPolicy policyException = Policy.Handle<TimeoutRejectedException>()
                    .Fallback(() =>
                    {
                        Console.WriteLine("Fallback");
                    });

                var policy = Policy.Timeout(3);
                //var cancellationToken = new CancellationToken();
                CancellationTokenSource userCancellationSource = new CancellationTokenSource();
                policy.Execute((token) =>
                {
                    Thread.Sleep(5000);
                    MessageBox.Show("aaa");

                }, userCancellationSource.Token);

                policyException.Wrap(policy);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            var r = GetRst();
            MessageBox.Show(r);
            //Task.Run(async () =>
            //{
            //    var r = await GetRstAsync();
            //    MessageBox.Show(r);
            //});
        }

        public string GetResult()
        {
            var s = "";

            try
            {
                ISyncPolicy policyException = Policy.Handle<TimeoutRejectedException>()
                    .Fallback(() =>
                    {
                        Console.WriteLine("Fallback");
                        s = "Fallback";
                    });
                ISyncPolicy policyTimeout = Policy.Timeout(5, Polly.Timeout.TimeoutStrategy.Pessimistic);
                ISyncPolicy mainPolicy = Policy.Wrap(policyTimeout, policyException);
                mainPolicy.Execute(() =>
                {
                    Console.WriteLine("Job Start...");
                    Thread.Sleep(15000);

                    //throw new Exception();
                    Console.WriteLine("Job End...");
                    s = $"{s}-OK";
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Unhandled exception : {ex.GetType()} : {ex.Message}");
                s = $"{s}-Error";
            }

            return s;
        }

        public string GetRqResult()
        {
            var s = "";

            var apiUrl = $"http://jinjianghoteltest.fanjiaxing.com/api/Hotel/GetHotelRoomList";
            var req = new HotelRoomStatusReq
            {
                InnId = "5573",
                EndOfDay = "2020-05-26",
                Days = 2
            };

            try
            {
                ISyncPolicy policyException = Policy.Handle<TimeoutRejectedException>()
                    .Fallback(() =>
                    {
                        Console.WriteLine("Fallback");
                        s = "Fallback";
                    });
                ISyncPolicy policyTimeout = Policy.Timeout(5, Polly.Timeout.TimeoutStrategy.Pessimistic);
                ISyncPolicy mainPolicy = Policy.Wrap(policyTimeout, policyException);
                mainPolicy.Execute(() =>
                {
                    Console.WriteLine("Job Start...");
                    //Thread.Sleep(15000);

                    var resultDto = WebRequestKit.PostAsJsonAsync<ApiResponse<Object>>(apiUrl, req).GetAwaiter().GetResult();
                    if (resultDto != null && resultDto.MsgCode == "0")
                    {
                        s = JsonConvert.SerializeObject(resultDto.Result);
                        //MessageBox.Show(retStr);
                    }
                    else
                    {
                        MessageBox.Show(
                            $"QueryRatePlanInfoAsync，HotelId:{req.InnId}，请求锦江之星接口获取酒店房价房型信息。{resultDto?.Message}");
                    }

                    //throw new Exception();
                    Console.WriteLine("Job End...");
                    s = $"{s}-OK";
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Unhandled exception : {ex.GetType()} : {ex.Message}");
                s = $"{s}-Error";
            }

            return s;

        }

        private async Task<string> GetRstAsync()
        {
            var apiUrl = $"http://jinjianghoteltest.fanjiaxing.com/api/Hotel/GetHotelRoomList";
            var req = new HotelRoomStatusReq
            {
                InnId = "5573",
                EndOfDay = "2020-05-26",
                Days = 2
            };

            var s = "";
            var policy = Policy.TimeoutAsync(3, TimeoutStrategy.Pessimistic);

            try
            {
                policy.ExecuteAsync(async () =>
                {
                    Thread.Sleep(5000);
                    var resultDto = WebRequestKit.PostAsJsonAsync<ApiResponse<Object>>(apiUrl, req).GetAwaiter().GetResult();
                    if (resultDto != null && resultDto.MsgCode == "0")
                    {
                        s = JsonConvert.SerializeObject(resultDto.Result);
                        //MessageBox.Show(retStr);
                    }
                    else
                    {
                        MessageBox.Show(
                            $"QueryRatePlanInfoAsync，HotelId:{req.InnId}，请求锦江之星接口获取酒店房价房型信息。{resultDto?.Message}");
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Unhandled exception : {ex.GetType()} : {ex.Message}");
                s = $"{s}-Error";
            }

            return s;
        }

        private string GetRst()
        {
            var apiUrl = $"http://jinjianghoteltest.fanjiaxing.com/api/Hotel/GetHotelRoomList";
            var req = new HotelRoomStatusReq
            {
                InnId = "5573",
                EndOfDay = "2020-05-26",
                Days = 2
            };

            var s = "";
            var policy = Policy.Timeout(3, TimeoutStrategy.Pessimistic);

            try
            {
                policy.Execute(() =>
                {
                    Thread.Sleep(5000);
                    var resultDto = WebRequestKit.PostAsJsonAsync<ApiResponse<Object>>(apiUrl, req).GetAwaiter().GetResult();
                    if (resultDto != null && resultDto.MsgCode == "0")
                    {
                        s = JsonConvert.SerializeObject(resultDto.Result);
                        //MessageBox.Show(retStr);
                    }
                    else
                    {
                        MessageBox.Show(
                            $"QueryRatePlanInfoAsync，HotelId:{req.InnId}，请求锦江之星接口获取酒店房价房型信息。{resultDto?.Message}");
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Unhandled exception : {ex.GetType()} : {ex.Message}");
                s = $"{s}-Error";
            }

            return s;
        }

        public async Task<string> GetRoomInfoAsync()
        {
            var s = "";

            //await Task.Delay(5000);

            //var apiUrl = $"http://jinjianghoteltest.fanjiaxing.com/api/Hotel/GetHotelRoomList";
            var apiUrl = $"http://localhost:62311/api/Hotel/GetHotelRoomList";
            var req = new HotelRoomStatusReq
            {
                InnId = "5573",
                EndOfDay = "2020-05-26",
                Days = 2
            };
            var resultDto = await WebRequestKit.PostAsJsonAsync<ApiResponse<Object>>(apiUrl, req);//.GetAwaiter().GetResult();
            if (resultDto != null && resultDto.MsgCode == "0")
            {
                s = JsonConvert.SerializeObject(resultDto.Result);
                //MessageBox.Show(retStr);
            }
            else
            {
                MessageBox.Show(
                    $"QueryRatePlanInfoAsync，HotelId:{req.InnId}，请求锦江之星接口获取酒店房价房型信息。{resultDto?.Message}");
            }

            return s;
        }

        public async Task<string> GetTestAsync()
        {
            var s = "";
            var timeoutPolicy = Policy.TimeoutAsync(5, TimeoutStrategy.Pessimistic);
            try
            {
                s = await timeoutPolicy
                    .ExecuteAsync(
                        async () => await GetRoomInfoAsync());
            }
            catch (Exception e)
            {
                s = e.Message;
            }
            return s;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //Task.Run(async () =>
            //{
            //    var r = await GetTestAsync();
            //    MessageBox.Show(r);
            //});

            List<Users> uList = new List<Users>();
            uList.Add(new Users
            {
                name = "aa",
                vno = "1"
            });
            uList.Add(new Users
            {
                name = "bb",
                vno = "2"
            });
            uList.Add(new Users
            {
                name = "cc",
                vno = "2"
            });

            var n = uList.GroupBy(m => m.vno).Count();//.ToList();
            MessageBox.Show(n.ToString());
        }
    }

    public class Users
    {
        public string name { get; set; }

        public string vno { get; set; }
    }
}
